package com.ct.interceptor;

import cn.hutool.log.StaticLog;
import com.ct.anno.LoginCheck;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class requestInfoHandlerInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // StaticLog.info("request host:{},{}", request.getRemoteAddr(), request.getRemotePort());
        StaticLog.info("requestInfo->{}:{}", request.getMethod(), request.getRequestURL());


        // 拦截方法和类上的注解做处理
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 让方法的优先级更高
            // 获取方法上面是否存在LoginCheck注解，如果存在并值是false.当然默认值也是false
            LoginCheck methodAnnotation = handlerMethod.getMethodAnnotation(LoginCheck.class);
            // methodAnnotation!=null 代表你加了注解,如果没加就不进入，就说明验证
            // !methodAnnotation.value() 加了如果是false，说明不需要验证了，就直接返回
            // 一句话：在开发中你要么不要加，要么加上去就使用默认值
            if (methodAnnotation != null && !methodAnnotation.value()) {
                return true;
            }

            // 然后就是类的优先级
            Class<?> beanType = handlerMethod.getBeanType();
            LoginCheck annotation = beanType.getAnnotation(LoginCheck.class);
            if (annotation != null && !annotation.value()) {
                return true;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
